package com.gr.catanddog_web.controller;

import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gr.catanddog_common.aspect.ApiOperationLog;
import com.gr.catanddog_common.damin.User;
import com.gr.catanddog_common.dao.UserMapper;
import com.gr.catanddog_common.utils.*;

import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.annotation.MultipartConfig;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.util.*;


@RestController
@Slf4j
@MultipartConfig()
/*@CrossOrigin(origins ="*",maxAge = 3600,allowCredentials = "true",allowedHeaders = "token")*/
public class SignInController {
    @Value("${web.url.path}")
    String webPath;

    @Value("${file.upload.url}")
    private  String filePath;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    SimpleDateFormat formatter;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private VerifyCode verifyCode;
    @PostMapping("/test")
    @ApiOperationLog(description = "测试接口")
    public Response test(@RequestBody @Validated User user) throws NoSuchAlgorithmException, InvalidKeyException {

        return Response.success(Token.tokenUtil(user,user, (long) (60*60)));
    }

    @PostMapping("/login")
    @ApiOperationLog(description = "登录")
    public Response login(@RequestParam("userName")String account,
                          @RequestParam("password")String password,
                          @RequestParam("code")String code,
                          @RequestParam("uuid")String  uuid) throws NoSuchAlgorithmException, InvalidKeyException {
        if(!Objects.requireNonNull(stringRedisTemplate.opsForValue().get(uuid)).equalsIgnoreCase(code)){
            return Response.fail("验证码错误");
        }
        User user = new User();user.setUserName(account);user.setPassword(password);
        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
        lqw.eq(User::getUserName,user.getUserName()).eq(User::getPassword,user.getPassword());
        User user1 = userMapper.selectOne(lqw);
        if(user1!=null){
            User user2 = new User();
            user2.setHeadPortrait(user1.getHeadPortrait());
            user2.setToken(user1.getToken());
            return Response.success(user2);
        }
        return Response.fail();
    }

    @PostMapping("/register")
    @ApiOperationLog(description = "注册")
    public Response register(@RequestParam("userName")String account,
                             @RequestParam("password")String password,
                             @RequestParam("code")String code,
                             @RequestParam("phone")String phone,
                             @RequestParam("uuid")String  uuid) throws NoSuchAlgorithmException, InvalidKeyException {
        User user = new User();
        user.setPhone(phone);
        user.setUserName(account);user.setPassword(password);user.setCode(code);user.setUuid(uuid);
        System.out.println(user.getCode());
        System.out.println(stringRedisTemplate.opsForValue().get(user.getUuid()));
        if(!Objects.requireNonNull(stringRedisTemplate.opsForValue().get(user.getUuid())).equalsIgnoreCase(user.getCode())){
            return  Response.fail("验证码错误");
        }
        String token = Token.tokenUtil(null,user, 0L);
        user.setToken(token);
        user.setHeadPortrait("http://124.223.224.5:8080/upload/1709195784614.jpg");
        user.setIat(formatter.format(new Date()));
        userMapper.insert(user);
        return Response.success(user.getToken());
    }
    @PostMapping("fileload")
    @ApiOperationLog(description = "文件上传")
    public Response fileLoad(@RequestParam("file") MultipartFile file) throws IOException {
        /*String fileName = String.valueOf(new Date().getTime())+".jpg";
        File dest = new File(filePath+'/'+fileName);
        file.transferTo(dest);*/
        String context = new String(file.getBytes());
        return Response.success(context);
    }
    @GetMapping("/getip")
    @ApiOperationLog(description = "获取客户端的ip地址")
    public Response getIp(HttpServletRequest hsr){
        String ip = GetIpAddress.getIpAddr(hsr);
        return  Response.success(ip);
    }
    /**
     * @description:
     * @author: 大睡大唬
     * @date: 2024/3/4 11:37
     * @param: [uid]
     * @return: com.gr.catanddog_common.utils.Response
     **/
    @GetMapping("/getcode")
    @ApiOperationLog(description = "获取验证码图片")
    public Response getImg(@RequestParam("uuid") String uid) throws IOException {
        String fileName = String.valueOf(new Date().getTime())+".jpg";
        File dest = new File(filePath+'/'+fileName);
        String s = VerifyCodeUtils.outputVerifyImage(100, 45, dest, 4);
        String url = webPath+fileName;
        String uuid;
        System.out.println(uid);
        if(!"undefined".equalsIgnoreCase(uid)&& !uid.isEmpty()){
            uuid = uid;
        }else uuid = UUID.randomUUID().toString();
        stringRedisTemplate.opsForValue().set(uuid,s);
        stringRedisTemplate.expire(uuid, Duration.ofSeconds(60*5));
        return Response.success(new VerifyCode(url, uuid));
    }
    @GetMapping("/getCode")
    @ApiOperationLog(description = "电话号码信息")
    public Response getCode(String phone) throws Exception {
        String code = "{\"code\":\""+RandomUtil.produceCode()+"\"}";
        SendSmsResponse sendSmsResponse = ALiYunSample.MsgRouting(phone, code);
        return Response.success(sendSmsResponse.body);
    }

/*    @GetMapping("/upload/*")
    @ApiOperationLog(description = "验证码图片获取")
    public void upload(ServletRequest servletRequest, ServletResponse servletResponse) throws IOException {
        String uri = servletRequest.getServletContext().getContextPath()+((HttpServletRequest)servletRequest).getServletPath();
        System.out.println(uri);
        String[] split = uri.split("/");
        for (String s : split) {
            System.out.print(s+"  ");
        }
        String filePath1 = filePath+'/'+split[2];
        File file = new File(filePath1);
        FileInputStream fin = new FileInputStream(file);
        IOUtils.copy(fin,servletResponse.getOutputStream());
        fin.close();
    }*/
}
